import { login } from '@/services/user';
import type { FunFirstParam } from '@/types';
import { ResponseCode } from '@/utils/request';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { ProFormText } from '@ant-design/pro-components';
import { Link } from '@umijs/max';
import { Button, Form, message, Space } from 'antd';
import React, { useState } from 'react';
import { history, useModel } from '@umijs/max';
import VerifyMessage from '../components/VerifyMessage';
import { GLOBAL_CONFIG, LOGIN_FROM_TAG } from '@/constant';

type SubmitParams = FunFirstParam<typeof login>;

const Login: React.FC = () => {
  const [errorMsg, setErrorMsg] = useState<string>();
  const [formRef] = Form.useForm();
  const { refresh: fetchUserInfo } = useModel('@@initialState');
  const [loading, setLoading] = useState(false);

  const handleSubmit = async () => {
    let values: SubmitParams;
    try {
      values = await formRef.validateFields();
    } catch (error: any) {
      return;
    }
    setLoading(true);
    try {
      // 登录
      const { code, message: msg } = await login({ ...values });
      switch (code) {
        case ResponseCode.Success: {
          setErrorMsg(undefined);
          message.success(msg || '登入成功', 1);
          GLOBAL_CONFIG.forceGetLoginInfo = true;
          // 尝试登入
          await fetchUserInfo();
          // 跳转上一次退出登录的路径 */
          setTimeout(() => {
            const redirect =
              window.sessionStorage.getItem(LOGIN_FROM_TAG) || '/';
            history.replace(redirect);
          }, 0);
          break;
        }
        case ResponseCode.Fail: {
          setErrorMsg(msg);
          break;
        }
      }
    } catch (error: any) {
      console.log(error);
      console.log('Verify => Login => handleSubmit', '请求失败');
    }
    setLoading(false);
  };

  return (
    <Form form={formRef}>
      {errorMsg && <VerifyMessage content={errorMsg} />}

      <ProFormText
        name="username"
        fieldProps={{
          size: 'large',
          prefix: <UserOutlined className="prefix-icon" />,
          autoComplete: 'username',
        }}
        placeholder={'用户名: '}
        rules={[
          {
            required: true,
            message: '请输入用户名!',
          },
        ]}
      />

      <ProFormText.Password
        name="password"
        fieldProps={{
          size: 'large',
          prefix: <LockOutlined className="prefix-icon" />,
          autoComplete: 'current-password',
        }}
        placeholder={'密码: '}
        rules={[
          {
            required: true,
            message: '请输入密码！',
          },
        ]}
      />

      <Button
        type="primary"
        style={{ width: '100%' }}
        size="large"
        onClick={handleSubmit}
        loading={loading}
      >
        登入
      </Button>

      <Space
        style={{ marginTop: 24, width: '100%', flexDirection: 'row-reverse' }}
      >
        <Link to="/verify/forget">忘记密码</Link>|
        <Link to="/verify/register">立即注册</Link>
      </Space>
    </Form>
  );
};

export default Login;
